package com.haipumi.back.actions;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.OperatingSystem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import com.haipumi.beans.HardDisk;
import com.haipumi.beans.ServiceInfo;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class BackServerAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2478262623283885132L;

	ServiceInfo si=new ServiceInfo();

	public ServiceInfo getSi() {
		return si;
	}

	public void setSi(ServiceInfo si) {
		this.si = si;
	}

	public String getServerInfo() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			// ServiceInfo si=new ServiceInfo();
			// System信息，从jvm获取
			property(request, response);
			// cpu信息
			cpu(request, response);
			// 内存信息
			memory(request, response);
			// 操作系统信息
			os(request, response);
			// 文件系统信息
			file(request, response);

			// super.outData(response, si);
			// re.setAttribute("ServiceInfo", si);
			HttpSession session = request.getSession();
			session.setAttribute("ServiceInfo", si);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return Action.SUCCESS;
	}

	private void file(HttpServletRequest request, HttpServletResponse response) throws SigarException {
		Sigar sigar = new Sigar();
        FileSystem fslist[] = sigar.getFileSystemList();
        //TODO 有bug fslist.length 长度为5  单实际所需要的长度为4
        
        List<HardDisk> hdlist=new ArrayList<HardDisk>();
//        for (int i = 0; i < fslist.length; i++) {
        for (int i = 0; i < 1; i++) {
        	HardDisk hd=new HardDisk();
        	//out.println("分区的盘符名称" + i);
        	
            FileSystem fs = fslist[i];
            // 分区的盘符名称
            //out.println("盘符名称:   " + fs.getDevName()+"<br/>");
            hd.setName(fs.getDevName());
            // 分区的盘符名称
            //out.println("盘符路径:   " + fs.getDirName()+"<br/>");
            //out.println("盘符标志:   " + fs.getFlags()+"<br/>");//
            // 文件系统类型，比如 FAT32、NTFS
            //out.println("盘符类型:   " + fs.getSysTypeName()+"<br/>");
           	hd.setSystypename(fs.getSysTypeName());
            // 文件系统类型名，比如本地硬盘、光驱、网络文件系统等
            //out.println("盘符类型名:  " + fs.getTypeName()+"<br/>");
            hd.setType(fs.getTypeName());
            FileSystemUsage usage = null;
            usage = sigar.getFileSystemUsage(fs.getDirName());
            switch (fs.getType()) {
            case 0: // TYPE_UNKNOWN ：未知
                break;
            case 1: // TYPE_NONE
                break;
            case 2: // TYPE_LOCAL_DISK : 本地硬盘
                // 文件系统总大小
            	//out.println(fs.getDevName() + "总大小:  " + usage.getTotal()/(1048576) + "GB"+"<br/>");
                hd.setTotalsize(Long.toString(usage.getTotal()/(1048576)));
                // 文件系统已经使用量
            	//out.println(fs.getDevName() + "已经使用量:    " + usage.getUsed()/(1048576) + "GB"+"<br/>");
                hd.setUsedsize(Long.toString(usage.getUsed()/(1048576)));
                break;
            case 3:// TYPE_NETWORK ：网络
                break;
            case 4:// TYPE_RAM_DISK ：闪存
                break;
            case 5:// TYPE_CDROM ：光驱
                break;
            case 6:// TYPE_SWAP ：页面交换
                break;
            }
            double temp=(usage.getUsed()/(1048576))/(usage.getTotal()/(1048576));
            hd.setZhanyonglv(Integer.toString((int)(temp*100)));
            hdlist.add(hd);
        }
        si.setDisklist(hdlist);
        return;
	}

	private void os(HttpServletRequest request, HttpServletResponse response) {
		OperatingSystem OS = OperatingSystem.getInstance();
		// out.println("操作系统名称: " + OS.getVendorName()+"<br/>");
		si.setSystemname(OS.getVendorName());
		// 操作系统的版本号
		// out.println("操作系统的版本号:   " + OS.getVersion()+"<br/>");
		si.setSystemversion(OS.getVersion());
	}

	private void cpu(HttpServletRequest request, HttpServletResponse response) throws SigarException {
		Sigar sigar = new Sigar();
		CpuInfo infos[] = sigar.getCpuInfoList();
		CpuPerc cpuList[] = null;
		cpuList = sigar.getCpuPercList();
		double temp = 0.0;
		for (int i = 0; i < 2; i++) {// 不管是单块CPU还是多CPU都适用
			CpuInfo info = infos[i];
			// out.println("CPU生产商: " + info.getVendor()+"<br/>");//
			// 获得CPU的卖主，如：Intel
			si.setCpumaker(info.getVendor());
			temp += printCpuPerc(cpuList[i], si, temp);
		}
		si.setCpuuse(Double.toString(temp / infos.length));
	}

	private double printCpuPerc(CpuPerc cpu, ServiceInfo si2, double temp) {
		temp+=cpu.getCombined();
    	return temp;
	}

	private void memory(HttpServletRequest request, HttpServletResponse response)
			throws SigarException {
		Sigar sigar = new Sigar();
		Mem mem = sigar.getMem();
		// 内存总量
		// out.println("内存总量:   " + mem.getTotal() / 1024L + "K av"+"<br/>");
		si.setRomtotal(Long.toString(mem.getTotal()));
		// 当前内存使用量
		// out.println("当前内存使用量:    " + mem.getUsed() / 1024L +
		// "K used"+"<br/>");
		si.setRomuse(Long.toString(mem.getUsed()));
	}

	private void property(HttpServletRequest request,
			HttpServletResponse response) throws UnknownHostException {
		Runtime r = Runtime.getRuntime();
		Properties props = System.getProperties();
		InetAddress addr;
		addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress();

		// out.println("本地ip地址: " + ip+"<br/>");
		si.setIp(ip);
		// out.println("本地主机名:  " + addr.getHostName()+"<br/>");
		si.setComputername(addr.getHostName());
		// out.println("JVM可以使用的处理器个数:  " + r.availableProcessors()+"<br/>");
		si.setCpunum(Integer.toString(r.availableProcessors()));
		// out.println("Java的运行环境版本：    " +
		// props.getProperty("java.version")+"<br/>");
		si.setJavaversion(props.getProperty("java.version"));
		// out.println("用户的当前工作目录：  " + props.getProperty("user.dir")+"<br/>");
		si.setUserdocument(props.getProperty("user.dir"));
	}
}
